package com.zengqingfa.juc.n4;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

/**
 * @fileName: SellTicket
 * @author: zengqf3
 * @date: 2021-6-12 8:47
 * @description:
 */
@Slf4j(topic = "c.SellTicket")
public class SellTicket {

    public static void main(String[] args) throws InterruptedException {
        TicketWindow window = new TicketWindow(2000);
        List<Thread> threadList = new ArrayList<>();
        List<Integer> sellCount = new Vector<>();
        for (int i = 0; i < 2000; i++) {
            Thread thread = new Thread(() -> {
                int sell = window.sell(randomAmount());
                sellCount.add(sell);
            });
            //线程安全实现
            threadList.add(thread);
            thread.start();
        }
        for (int i = 0; i < threadList.size(); i++) {
            threadList.get(i).join();
        }
        // 卖出去的票求和
        log.debug("selled count:{}", sellCount.stream().mapToInt(c -> c).sum());
        // 剩余票数
        log.debug("remainder count:{}", window.getCount());
    }

    // Random 为线程安全
    static Random random = new Random();

    // 随机 1~5
    public static int randomAmount() {
        return random.nextInt(5) + 1;
    }


}

class TicketWindow {

    private int count;

    public TicketWindow(int count) {
        this.count = count;
    }

    public int getCount() {
        return count;
    }

    /**
     * 卖票
     *
     * @param amount
     * @return
     */
    public synchronized int sell(int amount) {
        if (this.count >= amount) {
            this.count -= amount;
            return amount;
        } else {
            return 0;
        }
    }
}